package com.fwj.user.service.user.user;

import com.alibaba.fastjson.JSONObject;
import com.fwj.core.common.common.CommonUtils;
import com.fwj.core.common.constant.DataConstant;
import com.fwj.core.common.constant.UserConstant;
import com.fwj.core.common.execption.CommonException;
import com.fwj.user.api.user.UserService;
import com.fwj.user.dao.user.*;
import com.fwj.user.entity.user.*;
import com.fwj.core.common.model.ResponseDTO;
import com.fwj.core.common.model.ResponseEnum;
import com.fwj.user.model.user.UserDetailsInfo;
import com.fwj.user.model.user.UserExtendInfo;
import com.fwj.user.strategy.UserStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @Author: fwj
 * @Data: 2021/12/18 11:23
 * @Version 1.0
 * @Description:
 */

@Service
public class UserServiceImpl implements UserService {

    //添加日志工厂
    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserBaseInfoMapper userBaseInfoMapper;

    @Autowired
    private UserExtendMapper userExtendMapper;

    @Override
    @Transactional
    public ResponseDTO saveUser(UserDetailsInfo userDetailsInfo) {
        ResponseDTO responseDTO = new ResponseDTO();
        //转化JSON数据
        try {
            //获取策略并根据策略执行相应功能
            String strategy = userDetailsInfo.getStrategy();
            //策略枚举调用指定方法局部更新
            UserStrategy userStrategy = UserStrategy.matchStrategy(strategy);
            if (CommonUtils.isEmpty(userStrategy)) throw new CommonException(ResponseEnum.ERROR_PARAMETER);
            //执行策略
            userStrategy.execStrategy(userDetailsInfo,false);
            return responseDTO.success(ResponseEnum.SUCCESS);
        }catch (Exception e){
            LOGGER.error(e.toString());
            e.printStackTrace();
            return responseDTO.fail(ResponseEnum.SERVER_ERROR.getCode(),e.getMessage());
        }
    }

//    @Override
//    public void saveUserPersonalProfile(UserExtendInfo userExtendInfo, List<String> types, UserBaseInfo userBaseInfo) {
//        try {
//            int result = 0;
//            if (CommonUtils.isNotEmpty(userExtendInfo.getUserPersonalProfile())){
//
//                //获取最新的个人介绍
//                UserPersonalProfile oldUserPersonalProfile = new UserPersonalProfile();
//                oldUserPersonalProfile.setUserId(userBaseInfo.getId());
//                Example oldExample = setUserPersonalProfileExample(oldUserPersonalProfile);
//                oldUserPersonalProfile = userPersonalProfileMapper.selectOneByExample(oldExample);
//                if (CommonUtils.isNotEmpty(oldUserPersonalProfile)){
//                    //往个人介绍历史表添加记录
//                    UserPersonalProfileHistory userPersonalProfileHistory =
//                            JSONObject.parseObject(
//                                    JSONObject.toJSONString(oldUserPersonalProfile),
//                                    UserPersonalProfileHistory.class);
//                    userPersonalProfileHistory.setId(null);
//                    userPersonalProfileHistory.setCreateTime(oldUserPersonalProfile.getUpdateTime());
//                    userPersonalProfileHistoryMapper.insertSelective(userPersonalProfileHistory);
//                }
//
//                UserPersonalProfile userPersonalProfile = userExtendInfo.getUserPersonalProfile();
//
//                if (types.contains(UserConstant.USER_PERSONAL_PROFILE_INFO)){
//                    //更新用户个人介绍信息
//                    Example example = setUserPersonalProfileExample(userPersonalProfile);
//                    userPersonalProfile.setUpdateTime(new Date());
//                    result = userPersonalProfileMapper.updateByExampleSelective(userPersonalProfile,example);
//                }else {
//                    //创建用户个人介绍信息
//                    userPersonalProfile.setUserId(userBaseInfo.getId());
//                    userPersonalProfile.setType(UserConstant.USER_PERSONAL_PROFILE_INFO);
//                    userPersonalProfile.setCreateTime(new Date());
//                    userPersonalProfile.setUpdateTime(new Date());
//                    result = userPersonalProfileMapper.insertSelective(userPersonalProfile);
//                    saveUserExtendInfo(userPersonalProfile.getType(),userPersonalProfile.getUserId());
//                }
//                if (result==0)
//                    throw new IllegalStateException("更新用户个人介绍信息失败");
//            }else {
//                //如果扩展表有数据，则删除对应数据
//                if (types.contains(UserConstant.USER_PERSONAL_PROFILE_INFO)){
//                    UserPersonalProfile userPersonalProfile = new UserPersonalProfile();
//                    userPersonalProfile.setUserId(userBaseInfo.getId());
//                    //删除个人介绍表数据
//                    Example example = setUserPersonalProfileExample(userPersonalProfile);
//                    userPersonalProfile.setStatus(DataConstant.DELETED);
//                    userPersonalProfileMapper.updateByExampleSelective(userPersonalProfile,example);
//                    //删除userExtend表的记录
//                    deleteUserExtendInfo(UserConstant.USER_PERSONAL_PROFILE_INFO, userBaseInfo.getId());
//                }
//            }
//        }catch (IllegalStateException e){
//            throw new IllegalStateException("更新用户个人介绍信息失败");
//        }
//    }

    private void deleteUserExtendInfo(String type, Long userId) {
        UserExtend userExtend = new UserExtend();
        userExtend.setUserId(userId);
        Example example = setUserExtendExample(userExtend);
        userExtend.setType(type);
        userExtend.setIsModify(0);
        userExtend.setUpdateTime(new Date());
        userExtend.setStatus(DataConstant.DELETED);
        userExtendMapper.updateByExampleSelective(userExtend,example);
    }

    @Override
    public ResponseDTO savePersonalInfo(UserBaseInfo userBaseInfo) throws Exception{
        //如果没有相应信息则抛出异常
        UserBaseInfo execUserInfo = buildUserBaseInfo(userBaseInfo);
        userBaseInfoMapper.updateByPrimaryKeySelective(execUserInfo);
        return new ResponseDTO().success();
    }

    @Override
    public ResponseDTO getPersonalInfo(UserBaseInfo userBaseInfo) throws Exception{
        UserBaseInfo ret = userBaseInfoMapper.selectPersonalInterfaceInfo(userBaseInfo.getId(), UserConstant.NORMAL);
        return new ResponseDTO().success().setData(ret);
    }

    @Override
    public ResponseDTO saveProfilePhoto(UserDetailsInfo userDetailsInfo) {
        UserBaseInfo userBaseInfo = userDetailsInfo.getUserBaseInfo();
        UserBaseInfo execUserInfo = new UserBaseInfo();
        if (CommonUtils.isEmpty(userBaseInfo.getImage())){
            LOGGER.error("参数缺失");
            throw new CommonException(ResponseEnum.MISS_PARAMETER);
        }
        execUserInfo.setId(userBaseInfo.getId());
        execUserInfo.setImage(userBaseInfo.getImage());
        userBaseInfoMapper.updateByPrimaryKeySelective(execUserInfo);
        return new ResponseDTO().success();
    }

    @Override
    public UserBaseInfo findUserBaseInfoByUserNumber(Long userNumber) {
        try {
            return userBaseInfoMapper.findUserBaseInfoByUserNumber(userNumber,DataConstant.NORMAL);
        } catch (Exception e) {
            LOGGER.error(e.toString());
            throw new CommonException(ResponseEnum.SERVER_ERROR);
        }
    }

    private UserBaseInfo buildUserBaseInfo(UserBaseInfo userBaseInfo) {
        userBaseInfo.setCreateTime(null);
        userBaseInfo.setImage(null);
        userBaseInfo.setStatus(null);
        userBaseInfo.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        return userBaseInfo;
    }

    private Example setUserExtendExample(UserExtend userExtend) {
        Example example = new Example(UserExtend.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userExtend.getUserId());
        return example;
    }

    private void saveUserExtendInfo(String type,Long userId) {
        UserExtend userExtend = new UserExtend();
        userExtend.setUserId(userId);
        userExtend.setType(type);
        userExtend.setIsModify(1);
        userExtend.setCreateTime(new Date());
        userExtend.setUpdateTime(new Date());
        userExtend.setStatus(DataConstant.NORMAL);
        userExtendMapper.insertSelective(userExtend);
    }

    private List<UserExtend> getExtendList(UserExtend userExtend) {
        Example example = setUserExtendExample(userExtend);
        List<UserExtend> userExtends = userExtendMapper.selectByExample(example);
        return userExtends;
    }
    /**
     * @Description 冻结用户账户
     * @Param: jsonObject
     * @Author fwj
     * @return com.fwj.core.util.model.ResponseDTO
     * @Createtime 2021/12/23
     */
    @Override
    public ResponseDTO frozenUser(JSONObject jsonObject, UserBaseInfo user) {
        ResponseDTO responseDTO = new ResponseDTO();
        try {
//            //检查当前用户权限,如果是超级管理员权限或者是当前用户账号可以冻结
//            checkPower(user);
//            //冻结用户账户
//            UserBaseInfo userBaseInfo = new UserBaseInfo();
//            userBaseInfo.setUserNumber(Long.parseLong(jsonObject.getString("userNumber")));
//            Example example = setUserBaseInfoExample(userBaseInfo);
//            //设置用户为冻结态
//            userBaseInfo.setStatus(UserConstant.FROZEN);
//            userBaseInfoMapper.updateByExampleSelective(userBaseInfo,example);
            return responseDTO.success(ResponseEnum.SUCCESS.getCode(),"冻结账号成功");
        } catch (IllegalStateException e){
            return new ResponseDTO().fail(ResponseEnum.SERVER_ERROR.getCode(),e.getMessage());
        } catch (Exception e){
            return new ResponseDTO().fail(ResponseEnum.SERVER_ERROR.getCode(),"冻结账号失败");
        }
    }

    private boolean checkPower(UserBaseInfo user) {
        if (user==null)
            throw new IllegalStateException("您不具有操作权限");
        return true;
    }

    /**
     * @Description 获取用户信息
     * @Param: jsonObject
     * @Author fwj
     * @return com.fwj.core.util.model.ResponseDTO
     * @Createtime 2021/12/24
     */
    @Override
    public ResponseDTO getUserInfo(UserDetailsInfo userDetailsInfo) {
        ResponseDTO responseDTO = new ResponseDTO();
        //转化JSON数据
        try {
            //获取策略并根据策略执行相应功能
            String strategy = userDetailsInfo.getStrategy();
            //策略枚举调用指定方法局部更新
            UserStrategy userStrategy = UserStrategy.matchStrategy(strategy);
            if (CommonUtils.isEmpty(userStrategy)) throw new CommonException(ResponseEnum.ERROR_PARAMETER);
            //执行策略
            userStrategy.execStrategy(userDetailsInfo,true);
            return userStrategy.execStrategy(userDetailsInfo,true);
        }catch (Exception e){
            LOGGER.error(e.toString());
            e.printStackTrace();
            return responseDTO.fail(ResponseEnum.SERVER_ERROR.getCode(),e.getMessage());
        }
    }

    private UserDetailsInfo getUserPersonalInfo(JSONObject jsonObject, UserBaseInfo user) {
        UserDetailsInfo userDetailsInfo;
        //查询用户具有的扩展信息并存到types中
        List<String> types = getUserExtendTypes(user.getId());
        //获取用户数据
        userDetailsInfo = getUserExtendInfo(user.getId(),types);
        userDetailsInfo.setUserBaseInfo(user);
        return userDetailsInfo;
    }

    private List<String> getUserExtendTypes(Long id) {
        //查询用户具有的扩展信息并存到types中
        UserExtend userExtend = new UserExtend();
        userExtend.setUserId(id);
        List<UserExtend> userExtends = getExtendList(userExtend);
        List<String> types = new ArrayList<>();
        for(UserExtend ue:userExtends){
            types.add(ue.getType());
        }
        return types;
    }

    private UserDetailsInfo getUserExtendInfo(Long userId,List<String> types) {
        UserExtendInfo userExtendInfo = new UserExtendInfo();
        UserDetailsInfo userDetailsInfo = new UserDetailsInfo();
        try {
            //策略枚举调用指定方法进行局部查询
//            for (String type : types){
//                GetUserExtendInfoEnum getUserExtendInfoEnum = GetUserExtendInfoEnum.matchCode(type);
//                if (CommonUtils.isNotEmpty(getUserExtendInfoEnum))
//                    userExtendInfo = getUserExtendInfoEnum.getUserExtendInfo(userId,userExtendInfo);
//            }
            //封装用户扩展信息
            userDetailsInfo.setUserExtendInfo(userExtendInfo);
        } catch (IllegalStateException e){
            LOGGER.error(e.toString());
            throw new IllegalStateException(e.getMessage());
        }
        return userDetailsInfo;
    }

    private UserBaseInfo getUserBaseInfo(JSONObject jsonObject,UserBaseInfo user) {
        try {
            UserBaseInfo userBaseInfo = new UserBaseInfo();
            Long userNumber = Long.parseLong(jsonObject.getString("userNumber"));
            //校验是否具有操作权限
            checkPower(user);
            //设置查询条件
//            userBaseInfo.setUserNumber(Long.parseLong(userNumber));
//            Example example = setUserBaseInfoExample(userBaseInfo);
//            userBaseInfo = userBaseInfoMapper.selectOneByExample(example);
            //根据用户编码查询正常账户
            userBaseInfo = userBaseInfoMapper.findUserBaseInfoByUserNumber(userNumber,DataConstant.NORMAL);
            return userBaseInfo;
        }catch (IllegalStateException e){
            LOGGER.error(e.toString());
            throw new IllegalStateException("获取用户信息失败");
        }
    }

}
